package hui.zhang.web.action.system;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;

import hui.zhang.domain.system.Menu;
import hui.zhang.domain.system.User;
import hui.zhang.service.system.MenuService;
import hui.zhang.utils.BaseAction;

@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope("prototype")
@SuppressWarnings("all")
public class MenuAction extends BaseAction<Menu> {

	@Autowired
	private MenuService menuService;
	
	@Action(value = "menu_list")
	// 查询所有菜单
	public String list() {
		List<Menu> menus = menuService.findAll();
		toJsonAndResponse(menus);
		return NONE;
	}
	
	@Action(value = "menu_save",results = {
			@Result(name="success", type="redirect", location="/pages/system/menu.html")})
	public String save() {
		menuService.save(model);
		return SUCCESS;
	}
	
	// 动态显示菜单
	@Action(value="menu_showmenu")
	public String showMenu() {
		// 查询当前登录用户有什么菜单权限
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		List<Menu> menus = menuService.findByUser(user);
		System.out.println("====================");
		String jsonString = JSON.toJSONString(menus);
		System.out.println(ArrayUtils.toString(jsonString));
		System.out.println("====================");
		toJsonAndResponse(menus);
		return NONE;
	}
	
	@Action(value="menu_showadmin", results={@Result(name="success",location="/data/admin.json", type="redirect")})
	public String showAdmin() throws IOException {
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		if("admin".equals(user.getUsername())) {
			return SUCCESS;
		} else {
			return NONE;
		}
	}
}
